package com.pap.base.util.jackson;

import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pap.base.exception.JacksonException;

public class JacksonUtilss {

	// 利用静态内部类特性实现外部类的单例
	private static class ObjectMapperBuilder {
		private static final ObjectMapper mapper;
		static {
			mapper = new ObjectMapper();
			mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
			// 如果json字符串上面的属性比对象中的多的话，则会报错，默认加上这一行标注
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		}
	}

	public static final ObjectMapper getObjectMapper() {
		return ObjectMapperBuilder.mapper;
	}

	public static <T> T jsonToBean(String jsonStr, Class<T> cls) throws JacksonException {
		try {
			return getObjectMapper().readValue(jsonStr, cls);
		} catch (IOException e) {
			throw new JacksonException(e.getMessage());
		}
	}

	public static <T> T mapToBean(Map map, Class<T> cls) throws JacksonException {
		try {
			String json = getObjectMapper().writeValueAsString(map);
			return getObjectMapper().readValue(json, cls);
		} catch (IOException e) {
			throw new JacksonException(e.getMessage());
		}
	}

	public static String beanToJson(Object src) throws JacksonException {
		try {
			return getObjectMapper().writeValueAsString(src);
		} catch (JsonProcessingException e) {
			throw new JacksonException(e.getMessage());
		}
	}
}
